Skip to content

Method: CollectionInstanceContext(Collection, Class, Map)

1: /*
2: * JB4JSON-LD
3: * Copyright (C) 2024 Czech Technical University in Prague
4: *
5: * This library is free software; you can redistribute it and/or
6: * modify it under the terms of the GNU Lesser General Public
7: * License as published by the Free Software Foundation; either
8: * version 3.0 of the License, or (at your option) any later version.
9: *
10: * This library is distributed in the hope that it will be useful,
11: * but WITHOUT ANY WARRANTY; without even the implied warranty of
12: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13: * Lesser General Public License for more details.
14: *
15: * You should have received a copy of the GNU Lesser General Public
16: * License along with this library.
17: */
18: package cz.cvut.kbss.jsonld.deserialization;
19:
20: import cz.cvut.kbss.jopa.datatype.exception.DatatypeMappingException;
21: import cz.cvut.kbss.jsonld.exception.JsonLdDeserializationException;
22:
23: import java.util.Collection;
24: import java.util.Map;
25:
26: class CollectionInstanceContext<T extends Collection> extends InstanceContext<T> {
27:
28: private final Class<?> targetType;
29:
30: CollectionInstanceContext(T instance, Map<String, Object> knownInstances) {
31: super(instance, knownInstances);
32: this.targetType = null;
33: }
34:
35: CollectionInstanceContext(T instance, Class<?> targetType, Map<String, Object> knownInstances) {
36: super(instance, knownInstances);
37: this.targetType = targetType;
38: }
39:
40: /**
41: * Adds the specified item into this collection.
42: *
43: * @param item The item to add
44: */
45: @Override
46: void addItem(Object item) {
47: if (targetType == null) {
48: instance.add(item);
49: return;
50: }
51: try {
52: final Object toAdd = resolveAssignableValue(targetType, item);
53: instance.add(toAdd);
54: } catch (DatatypeMappingException e) {
55: throw new JsonLdDeserializationException("Type mismatch when adding item " + item + " to collection.", e);
56: }
57: }
58:
59: @Override
60: Class<?> getItemType() {
61: return targetType;
62: }
63: }